#include <mpi.h>
#include <stdio.h>
#include "utils.h"

int main(int argc, char *argv[]) {
    MPI_Init(&argc, &argv);

    int world_rank, world_size;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    // 启动子进程
    MPI_Comm intercomm;
    char *command      = "./child"; // 子进程的可执行文件
    char *argv_child[] = { NULL };
    int maxprocs       = 2;         // 启动2个子进程
    MPI_Info info      = MPI_INFO_NULL;
    int root           = 0;        // 只有rank 0的进程负责启动子进程
    MPI_Comm_spawn(command, argv_child, maxprocs, info, root, 
            MPI_COMM_WORLD, &intercomm, MPI_ERRCODES_IGNORE);

    // 与子进程通信
    int child_rank, child_size;
    MPI_Comm_remote_size(intercomm, &child_size);

    //! 传入组间通信子时返回的还是本地组的rank排名[From DeepSeek]
    MPI_Comm_rank(intercomm, &child_rank);
    // INFO("rank = %d, child_rank = %d\n", world_rank, child_rank);

    if (world_rank == 0) {
        int message = 42;
        MPI_Send(&message, 1, MPI_INT, 0, 0, intercomm);
        INFO("Parent process %d sent message %d to child process 0!\n", world_rank, message);
    }

    MPI_Finalize();
    return 0;
}